package org.feidao.chapter82.common;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.feidao.chapter82.model.Heroic;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by linghufeixia on 2022-11-8.
 */
public class serializeUtil {
    public static byte[] serializeObjToByte(Heroic heroic) {
        if (heroic == null) {
            return null;
        }
        Schema<Heroic> schema = RuntimeSchema.getSchema(Heroic.class);
        LinkedBuffer buffer = LinkedBuffer.allocate(4096);
        byte[] protostuff = null;
        try {
            protostuff = ProtostuffIOUtil.toByteArray(heroic, schema, buffer);
        } finally {
            buffer.clear();
        }
        return protostuff;
    }

    public static List<byte[]> serializeListToByte(List<Heroic> list) {
        if (list == null || list.size() <= 0) {
            return null;
        }
        List<byte[]> bytes = new ArrayList<>();
        Schema<Heroic> schema = RuntimeSchema.getSchema(Heroic.class);
        LinkedBuffer buffer = LinkedBuffer.allocate(4096);
        byte[] protostuff = null;
        for (Heroic heroic : list) {
            try {
                protostuff = ProtostuffIOUtil.toByteArray(heroic, schema, buffer);
                bytes.add(protostuff);
            } finally {
                buffer.clear();
            }
        }
        return bytes;
    }

    public static Heroic deserializeByteToObj(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        Schema<Heroic> schema = RuntimeSchema.getSchema(Heroic.class);
        List<Heroic> list = new ArrayList<Heroic>();

        Heroic heroic = new Heroic();
        ProtostuffIOUtil.mergeFrom(bytes, heroic, schema);
        return heroic;
    }

    public static List<Heroic> deserializeByteToList(
            List<byte[]> bytesList) {
        if (bytesList == null || bytesList.size() <= 0) {
            return null;
        }
        Schema<Heroic> schema = RuntimeSchema.getSchema(Heroic.class);
        List<Heroic> list = new ArrayList<Heroic>();
        for (byte[] bs : bytesList) {
            Heroic product = new Heroic();
            ProtostuffIOUtil.mergeFrom(bs, product, schema);
            list.add(product);
        }
        return list;
    }
}
